package com.shenganyuan.smac.check;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.oklib.utils.Logger.Logger;
import com.oklib.utils.helper.RxUtil;
import com.oklib.utils.network.http.ViseHttp;
import com.oklib.utils.network.http.callback.ACallback;
import com.oklib.utils.network.http.callback.UCallback;
import com.oklib.utils.network.http.subscriber.ApiCallbackSubscriber;
import com.oklib.utils.view.SnackbarUtil;
import com.oklib.utils.view.ToastUtils;
import com.oklib.widget.dialog.ConfirmDialog;
import com.oklib.widget.recyclerview.BaseQuickAdapter;
import com.oklib.widget.recyclerview.BaseViewHolder;
import com.shenganyuan.smac.App;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.adapter.ImagePickerAdapter;
import com.shenganyuan.smac.common.BaseActivity;
import com.shenganyuan.smac.common.Config;
import com.shenganyuan.smac.common.beans.ApiActivitys;
import com.shenganyuan.smac.common.beans.ApiRiskInfos;
import com.shenganyuan.smac.common.beans.EventRefreshPage;
import com.shenganyuan.smac.common.beans.LocationInfo;
import com.shenganyuan.smac.common.beans.RiskPoint;
import com.shenganyuan.smac.common.beans.RiskResource;
import com.shenganyuan.smac.common.data.AnyPrefUtil;
import com.shenganyuan.smac.common.data.Api;
import com.shenganyuan.smac.common.utils.DataConverter;
import com.shenganyuan.smac.common.view.CommonSelectDialog;
import com.shenganyuan.smac.common.view.RecyclerViewItemDivider;
import com.shenganyuan.smac.position.ActSetPosition;
import com.shenganyuan.smac.risk.ActRiskInfoAdd;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.shenganyuan.smac.common.Config.PIC_COMPRESS_SIZE;

/**
 * 巡查信息录入
 *
 * @author Damon
 */

public class ActCheckInfoAdd extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {
    @BindView(R.id.work_risk_infos_recycler)
    RecyclerView recycler;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.activitys)
    TextView activity;
    @BindView(R.id.work_check_frequence)
    TextView work_check_frequence;
    @BindView(R.id.txt_check_position)
    TextView txt_check_position;
    @BindView(R.id.action_save)
    TextView action_save;
    @BindView(R.id.et_send)
    EditText etSend;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.container_check_add)
    LinearLayout container_check_add;
    ConfirmDialog confirmDialog;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private BaseQuickAdapter baseQuickAdapter;
    List<ApiActivitys.GkzyhdBean> gkzyhdBeans;
    ApiActivitys.GkzyhdBean currentGkzyhdBean;

    @Override
    public int getLayoutId() {
        return R.layout.act_check_info_add;
    }

    @Override
    public void initUI(@Nullable Bundle savedInstanceState) {

        recycler.addItemDecoration(new RecyclerViewItemDivider(mContext, LinearLayoutManager.VERTICAL)
                .setAppearance(20, "#eeeeee"));
        recycler.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
        recyclerView.setHasFixedSize(true);

    }

    /**
     * 发现隐患
     *
     * @param item
     * @param v
     */
    private void foundRisk(RiskResource item, View v) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        //危险源id
        bundle.putSerializable("riskResource", item);
        //风险点id
        String riskPointId = getIntent().getStringExtra("pointId");
        bundle.putString("gkzydyid", riskPointId);
        intent.putExtras(bundle);
        intent.setClass(mContext, ActRiskInfoAdd.class);
        startActivity(intent);
    }

    @Override
    public void initData() {
        setTitle("巡查信息录入");
        String txt = getResources().getStringArray(R.array.array_work_check_frquence)[0];
        work_check_frequence.setText(txt);

        baseQuickAdapter = new BaseQuickAdapter<RiskResource, BaseViewHolder>(R.layout.act_risk_info_item) {
            @Override
            protected void convert(BaseViewHolder helper, RiskResource item) {
                //检查对象
                helper.setText(R.id.tv_check_position, item.getBsdx());
                //危险源
                helper.setText(R.id.tv_risk_resource, item.getBsnr());
                helper.setText(R.id.tv_risk_type, item.getSglx());
                helper.setText(R.id.tv_risk_level, item.getPjJb());
                //典型控制措施
                helper.setText(R.id.tv_operation_method, item.getDxgzcs());
//                helper.setText(R.id.tv_time, DataConverter.getDateStr(item.getLrTime()));
                helper.setText(R.id.to_change_txt, "发现隐患").addOnClickListener(R.id.to_change_txt);
                helper.getView(R.id.to_change).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        foundRisk(item, v);
                    }
                });
                helper.getView(R.id.to_change_txt).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        foundRisk(item, v);
                    }
                });
            }
        };
        recycler.setAdapter(baseQuickAdapter);

        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(mContext, selImageList, Config.PIC_SIZE);
        adapter.setOnItemClickListener(this);
        recyclerView.setAdapter(adapter);
        getActivitysAndRisks();
    }


    private void getActivitysAndRisks() {
        String riskPointId = getIntent().getStringExtra("pointId");
        String zq = getFrequencyQueryStr();
        ViseHttp.RETROFIT().create(Api.class).getZyhdlist(App.getCurrentUser().getId(), riskPointId, zq, App.getAccessToken())
                .subscribeOn(Schedulers.io())
                .doOnNext(new Consumer<ApiActivitys>() {
                    @Override
                    public void accept(ApiActivitys data) throws Exception {
                        if (gkzyhdBeans != null && gkzyhdBeans.size() > 0) {
                            currentGkzyhdBean = null;
                            gkzyhdBeans.clear();
                        }
                        if (data != null && "true".equalsIgnoreCase(data.getResult())) {
                            if (data.getGkzyhd() != null && data.getGkzyhd().size() > 0) {
                                gkzyhdBeans = data.getGkzyhd();
                                currentGkzyhdBean = data.getGkzyhd().get(0);
                            }
                        }
                    }
                })
                .concatMap(new Function<ApiActivitys, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(ApiActivitys data) throws Exception {
                        String activityId = "";
                        if (data != null && "true".equalsIgnoreCase(data.getResult())) {
                            if (data.getGkzyhd() != null && data.getGkzyhd().size() > 0) {
                                activityId = currentGkzyhdBean.getId();
                            }
                        }
                        return ViseHttp.RETROFIT().create(Api.class).getRiskInfos(App.getCurrentUser().getId(), riskPointId, activityId, zq, App.getAccessToken());
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiCallbackSubscriber(new ACallback<ApiRiskInfos>() {
                    @Override
                    public void onSuccess(ApiRiskInfos apiRisk) {
                        activity.setText(currentGkzyhdBean == null ? "" : currentGkzyhdBean.getName());
                        operateResult(apiRisk);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        SnackbarUtil.showShort(getWindow().getDecorView(), "获取信息失败");
                    }
                }));
    }

    private void getRiskInfos(String activityId) {
        String riskPointId = getIntent().getStringExtra("pointId");
        String zq = getFrequencyQueryStr();
        ViseHttp.RETROFIT().create(Api.class).getRiskInfos(App.getCurrentUser().getId(), riskPointId, activityId, zq, App.getAccessToken())
                .compose(RxUtil.rxSchedulerHelper())
                .subscribe(new ApiCallbackSubscriber(new ACallback<ApiRiskInfos>() {
                    @Override
                    public void onSuccess(ApiRiskInfos apiRisk) {
                        operateResult(apiRisk);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        SnackbarUtil.showShort(getWindow().getDecorView(), "获取信息失败");
                    }
                }));
    }

    private void operateResult(ApiRiskInfos apiRisk) {
        try {
            //
            // 扫描二维码上传风险点和用户ID获取当前用户当前风险点的所有危险源信息，
            // 获取风险点所有危险源后应判断该风险点是否设置过GPS位置（判断条件是查看返回信息中的djzydy:GPS是否为空），
            // 并判断当前用户所在位置与风险点设置GPS坐标是否偏离过大（暂定1000米），以上两个条件都为真是可进入巡查信息录入。
            RiskPoint riskPoint = apiRisk.getGkzydy();
            if (riskPoint == null || TextUtils.isEmpty(riskPoint.getGps())) {
                showSetPositionDialog();
            } else {
                //设置巡查点标题
                txt_check_position.setText(riskPoint.getName());
                //已经设置过了则显示隐患信息列表
                List<RiskResource> gkwxbs = apiRisk.getGkwxbs();
                baseQuickAdapter.setNewData(gkwxbs);
                baseQuickAdapter.notifyDataSetChanged();
                //判断风险点位置和当前位置的距离是否小于1KM，小于1Km之内才能显示添加按钮(才能进入巡查信息页面)
                String isInStr = isIn(riskPoint);
                boolean isIn = TextUtils.isEmpty(isInStr);
                container_check_add.setVisibility(isIn ? View.VISIBLE : View.GONE);
                action_save.setVisibility(isIn ? View.VISIBLE : View.GONE);
                if (!isIn) {
                    if (confirmDialog != null) {
                        confirmDialog.dismiss();
                        confirmDialog = null;
                    }
                    confirmDialog = new ConfirmDialog(mContext);
                    confirmDialog.setCancelable(false);
                    confirmDialog.setTitle("无法录入巡查信息");
                    confirmDialog.setMessage(isInStr).setPositiveButton("知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            confirmDialog.dismiss();
                            finish();
                        }
                    }).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存数据
     * pcyhxxid	是	String	风险点ID（gkZydyId）
     * pczgjl	是	String	整改内容最大值100字内
     * gps	是	String	GPS位置（***;***）
     * djuserid	是	String	登录用户ID
     * picfile	是	String	照片名 如多文件上传文件名加序号
     * token	是	String	登录返回值access_token
     */
    private void operateData() {
        String gkzydyid = getIntent().getStringExtra("pointId");//风险点id
        String xcjl = etSend.getText().toString().trim();
        if (TextUtils.isEmpty(gkzydyid)) {
            SnackbarUtil.showShort(getWindow().getDecorView(), "信息不完整");
            return;
        }
        if (TextUtils.isEmpty(xcjl)) {
            SnackbarUtil.showShort(getWindow().getDecorView(), "内容不能为空");
            return;
        }
        if (selImageList == null || selImageList.size() <= 0) {
            SnackbarUtil.showShort(getWindow().getDecorView(), getResources().getString(R.string.str_msg_pic_must_one));
            return;
        }
        if (currentGkzyhdBean == null) {
            SnackbarUtil.showShort(getWindow().getDecorView(), "作业活动信息为空，无法保存");
            return;
        }
        List<String> pathsToCompress = new ArrayList<>();
        if (selImageList != null) {
            for (int i = 0; i < selImageList.size(); i++) {
                String path = selImageList.get(i).path;
                pathsToCompress.add(path);
            }
        }
        progress.setVisibility(View.VISIBLE);
        List<String> pathsCompressResult = new ArrayList<>();

        Luban.with(this)
                .load(pathsToCompress)                                   // 传人要压缩的图片列表
                .ignoreBy(PIC_COMPRESS_SIZE)                                  // 忽略不压缩图片的大小
                .setTargetDir(Config.APP_CARD_PATH_PICTURE_COMPRESS)                        // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        Logger.e("开始压缩");
                    }

                    @Override
                    public void onSuccess(File file) {
                        Logger.e(file.getPath() + "   压缩成功");
                        pathsCompressResult.add(file.getPath());
                        //压缩完成
                        if (pathsCompressResult.size() == pathsToCompress.size()) {
                            toSave(pathsCompressResult);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        progress.setVisibility(View.GONE);
                        SnackbarUtil.showShort(getWindow().getDecorView(), "文件压缩失败，请重试");
                    }
                }).launch();    //启动压缩


    }

    /**
     * 提交数据
     *
     * @param pathsCompressResult
     */
    private void toSave(List<String> pathsCompressResult) {
        String djuserid = App.getCurrentUser().getId();
        String zq = getFrequencyQueryStr();
        String gkzydyid = getIntent().getStringExtra("pointId");//风险点id
        String xcjl = etSend.getText().toString().trim();
        String gps = "";
        LocationInfo locationInfo = AnyPrefUtil.getLocationInfo();
        if (locationInfo != null) {
            gps = locationInfo.longitude + ";" + locationInfo.latitude;
        }
        String token = App.getAccessToken();
        Map<String, String> req = new HashMap<>();
        req.put("djuserid", djuserid);
        req.put("zq", zq);
        req.put("gkzydyid", gkzydyid);
        req.put("xcjl", xcjl);
        req.put("zyhdid", currentGkzyhdBean.getId());
        req.put("gps", gps);
        req.put("token", token);
        req.put("dwxxId", App.getCurrentUser().getDwxxId());
        Map<String, File> files = new HashMap<>();
        for (int i = 0; i < pathsCompressResult.size(); i++) {
            String path = pathsCompressResult.get(i);
            files.put("picfile" + i, new File(path));
        }
        ViseHttp.UPLOAD("xcxxsave", new UCallback() {
            @Override
            public void onProgress(long currentLength, long totalLength, float percent) {
                if (percent == 100) {

                }
                progress.setProgress((int) percent);
                action_save.setClickable(false);
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                Logger.i("upload errorCode:" + errCode + ",errorMsg:" + errMsg);
            }
        }).addParams(req)
                .addFiles(files)
                .request(new ACallback<Object>() {
                    @Override
                    public void onSuccess(Object data) {
                        ToastUtils.showToast(mContext, "巡查信息保存成功");
                        EventBus.getDefault().post(new EventRefreshPage(Config.EventKit.KEY_EVENT_REFRESH_ACTCHECKRECORDS));
                        finish();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        action_save.setClickable(true);
                        progress.setVisibility(View.GONE);
                        Logger.i("upload errorCode:" + errCode + ",errorMsg:" + errMsg);
                    }
                });
    }

    /**
     * 判断当前位置是否在给定位置的1000米之内
     *
     * @return
     */
    private String isIn(RiskPoint riskPoint) {
        LatLng mLocation1 = DataConverter.fromStrToLatLng(riskPoint.getGps());
        //该风险点没有位置信息则不能录入巡查信息
        if (mLocation1 == null) {
            Logger.e("该风险点没有位置信息则不能录入巡查信息！");
            return "该风险点没有位置信息则不能录入巡查信息！";
        }
        //当前位置
        LatLng mLocation2 = DataConverter.fromStrToLatLng(null);
        if (mLocation2 == null) {
            Logger.e("当前位置信息为空！");
            return "当前位置信息为空！";
        }
        int distance = (int) AMapUtils.calculateLineDistance(mLocation1, mLocation2);
//        Logger.e("当前位置和风险点定位之间的距离是：" + distance);
//        return distance <= Config.POSITION_CIRCLE ? "" : "您距离当前风险点太远了";
        return "";
    }

    /**
     * 设置巡查点
     */
    private void showSetPositionDialog() {
        if (confirmDialog != null) {
            confirmDialog.dismiss();
            confirmDialog = null;
        }
        confirmDialog = new ConfirmDialog(mContext);
        confirmDialog.setMessage("您尚未设置巡查位置，点击确定去设置").setPositiveButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到巡查位置设置页面
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                String riskPointId = getIntent().getStringExtra("pointId");
                bundle.putString("pointId", riskPointId);
                intent.setClass(mContext, ActSetPosition.class);
                intent.putExtras(bundle);
                startActivity(intent);
                confirmDialog.dismiss();
            }
        }).setNevigateButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        }).show();
    }


    @OnClick({R.id.action_save, R.id.activitys, R.id.work_check_frequence})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.work_check_frequence:
                popWorkFrequence(view);
                break;
            case R.id.activitys:
                popActivitys(view);
                break;
            case R.id.action_save:
                operateData();
                break;
        }
    }


    /**
     * 活动选择
     */
    private void popActivitys(View view) {
        PopupMenu popupMenu = new PopupMenu(this, view);
        Menu menu = popupMenu.getMenu();
        for (int i = 0; i < gkzyhdBeans.size(); i++) {
            menu.add(android.view.Menu.NONE, android.view.Menu.NONE + i, i, gkzyhdBeans.get(i).getName());
        }
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                currentGkzyhdBean = gkzyhdBeans.get(item.getItemId());
                String activityId = currentGkzyhdBean.getId();
                activity.setText(currentGkzyhdBean == null ? "" : currentGkzyhdBean.getName());
                getRiskInfos(activityId);
                return true;
            }
        });
        popupMenu.show();
    }

    /**
     * 检查频率选择
     */
    private void popWorkFrequence(View view) {
        PopupMenu popupMenu = new PopupMenu(this, view);
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                onFrequenceChosed(item);
                return true;
            }
        });
        popupMenu.inflate(R.menu.menu_work_frequence);
        popupMenu.show();
    }

    private String getFrequencyQueryStr() {
        String[] arra = mContext.getResources().getStringArray(R.array.array_work_check_frquence);
        String currentTxt = work_check_frequence.getText().toString();
        String string = null;
        int index = 0;
        for (int i = 0; i < arra.length; i++) {
            string = arra[i];
            if (string.equals(currentTxt)) {
                index = i;
            }
        }
        String result = "A";
        switch (index) {
            case 0:
                result = "A";
                break;
            case 1:
                result = "B";
                break;
            case 2:
                result = "C";
                break;
            case 3:
                result = "D";
                break;
            case 4:
                result = "E";
                break;
        }
        return result;
    }

    private void onFrequenceChosed(MenuItem item) {
        int position = 0;
        switch (item.getItemId()) {
            case R.id.work_menu_day:
                position = 0;
                break;
            case R.id.work_menu_week:
                position = 1;
                break;
            case R.id.work_menu_month:
                position = 2;
                break;
            case R.id.work_menu_quarter:
                position = 3;
                break;
            case R.id.work_menu_year:
                position = 4;
                break;
        }
        String txt = getResources().getStringArray(R.array.array_work_check_frquence)[position];
        work_check_frequence.setText(txt);
        getActivitysAndRisks();

    }


    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                ArrayList<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                CommonSelectDialog selectDialog = CommonSelectDialog.newInstance(names);
                selectDialog.addOnSingleCheckListener(new CommonSelectDialog.OnSingleCheckListener() {
                    @Override
                    public void onSingleCheck(int position, String value) {
                        ToastUtils.showToast(mContext, value);
                        switch (position) {
                            case 0: // 直接调起相机
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(Config.PIC_SIZE - selImageList.size());
                                Intent intent = new Intent(mContext, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(Config.PIC_SIZE - selImageList.size());
                                Intent intent1 = new Intent(mContext, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }
                    }
                });
                selectDialog.show(getSupportFragmentManager(), "choose_operation");
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(mContext, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (currentGkzyhdBean != null) {
            getRiskInfos(currentGkzyhdBean.getId());
        }
    }
}
